<?php
/*
 * Parser for the nwiki.  Will accept the 
 * mediawiki sintax.
 * Created by Didac Calventus at dfwikiteam
 * based on a parser library created by Ferran Recio
 * for Bluew Web and DFwiki
 * This parser is distributed under GPL licence
 */
require_once($CFG->dirroot."/lib/weblib.php");		// required to replace smilies  
require_once($CFG->dirroot."/lib/locallib.php");  
require_once($CFG->dirroot."/mod/wiki/locallib.php");

$regex = array();
$tocheaders = array();		// will use this to create the TOC
$references = array();		// will use this to create the reference list
$nreference = -1;
$nowikitext = array();
$nowikicounter = 0;

$authorname = '';
$content = '';
$courseid = 0;
$entryid = 0;
$groupid = 0;
$pagename = '';
$userid = 0;
$wikiid = 0;

function parse_nwiki_to_html($course, $wiki, $entry, $page) {
	global $regex, $nowikitext, $tocheaders, $pagename, $content, $courseid, $entryid, $authorname, $wikiid, $userid, $groupid, $nowikicounter, $nreference;
	
	$authorname = $page->author;
	$content = $page->content;
	$courseid = $course;
	$entryid = $entry;
	$groupid = $page->groupid;
	$pagename = $page->pagename;
	$userid = $page->userid;
	$wikiid = $wiki;
	$nowikicounter = 0;
	$nreference = -1;
	
	// direct transformations
    $regex['replace'] = array (
	    '/{{wikibook:.*?}}/' => '',
	    "/'''''(.*?)'''''/"  => '<b><i>\\1</i></b>',
	    "/'''(.*?)'''/"      => '<b>\\1</b>',
	    "/''(.*?)''/"        => '<i>\\1</i>', 
	    "/\*\*(.*?)\*\*/"    => '<b>\\1</b>', // creole syntax
	    '/^-{3,4}/m'         => "</p><hr /><p>",
	    '/^ (.*?)$/m'        => '</p><pre class="quote">\\1</pre><p>',
	    '/^%%%/m'            => '<br />', // creole syntax
	    '/\\\\\\\\/'         => '<br />', // creole syntax
    );

    // non direct transformations
    $regex['variable'] = array (
        '/^=+(.*?)=+/m'              => 'nwiki_parse_header',
        '/(\[\[Image:)(.*?)\]\]/'    => 'nwiki_parse_image',
        '/\{\{(<<ThisIsThePlaceOfTheNoWikiText-\d+>>)(\|(.*?))?\}\}/'
                                     => 'nwiki_parse_creole_image',
        '/(\[\[attach:)(.*?)\]\]/'   => 'nwiki_parse_attach',
        '/(\[|\[\[)(<<ThisIsThePlaceOfTheNoWikiText-\d+>>)(\ (.*?))?(\|(.*?))?(\]\]|\])/'
                                     => 'nwiki_parse_external_link',                                     
        '/\[\[#(.*?)\]\]/'           => 'nwiki_parse_anchor',
        '/\[\[(.*?)\]\]/'            => 'nwiki_parse_internal_link',
        '/^\{\|(.*?)\|\}/sm'         => 'nwiki_parse_table',
        '/(^\|[^\n]*\|\n)+/sm'       => 'nwiki_parse_creole_table',
        '/(^(\*|#|:)+.*?(\n|$))+/sm' => 'nwiki_parse_list',
        '/(^;.*?:.*?(\n|$))+/sm'     => 'nwiki_parse_definition_list',
        '/~{5}/'                     => 'nwiki_parse_datetime',
        '/~{4}/'                     => 'nwiki_parse_username_datetime',
        '/~{3}/'                     => 'nwiki_parse_username',
        '/<ref name="(.*?)"\/?>((.*?)<\/ref>)?/'  
                                     => 'nwiki_parse_references',
        '/<references\/>/'           => 'nwiki_parse_reference_list',
    );

    $regex['nowiki'] = array (
	    "/<nowiki>(.*?)<\/nowiki>/s" => 'nwiki_parse_nowiki',
	    "/\{\{\{(.*?)\}\}\}/s" => 'nwiki_parse_nowiki',
	    "/((http|https|ftp):\/\/[\w!~*'\(\).;?:@&=+$,%#-\/]+)/" => 'nwiki_parse_nowiki',
    );

	// Remove carriage returns
	$text = str_replace("\r", "", $content);
	foreach($regex['nowiki'] as $match => $func){
		$text = preg_replace_callback($match, $func, $text);
	}

	foreach($regex['variable'] as $match => $func){
		$text = preg_replace_callback($match, $func, $text);
	}

	// $find will contain the regex to find
	$find = array_keys($regex['replace']);
	// $replace will contain the replacements of items in $find
	$replace = array_values($regex['replace']);
	
	$text2 =  preg_replace($find, $replace, $text);
							
	foreach($nowikitext as $index => $singlenowikitext){	
		$text2 = preg_replace("/<<ThisIsThePlaceOfTheNoWikiText-{$index}>>/", $singlenowikitext, $text2);
	}

	// here comes the TOC, search for --TOC-- and include the real TOC
    $toc = nwiki_parse_toc($tocheaders);
    $text2 = str_replace("NWikiTableOfContents", $toc, $text2);
	
	$text2 = preg_replace('/^\n/m', '</p><p>', $text2);
	
	// remove empty paragraphs
	$text2 = preg_replace('/<p>\s*<\/p>/s', '', "<p>$text2</p>");
	
	// join consecutive pre blocks
	$text2 = preg_replace('/<\/pre>\s*<pre class="quote">/s', '<br />', $text2);
	
    $options->para=false;
	return '<html><body>'.format_text($text2,FORMAT_HTML,$options).'</body><html>';
}


function nwiki_parse_username($matches) {
	global $authorname;
	
	$author = get_record('user', 'username', $authorname);

	return $author->firstname." ".$author->lastname;
}

function nwiki_parse_username_datetime($matches) {
	global $authorname;
	
	$author = get_record('user', 'username', $authorname);
	
	return $author->firstname." ". $author->lastname.", ".strftime('%x')." - ".strftime('%X');
}

function nwiki_parse_datetime($matches) {
	return strftime('%x')." - ".strftime('%X');
}

function nwiki_parse_nowiki($matches) {
	global $nowikitext, $nowikicounter;

	$parsednowiki = preg_replace("/</","&lt;", $matches[1]);
	$parsednowiki = preg_replace("/>/","&gt;", $parsednowiki);
	$parsednowiki = preg_replace("/\n /","<br />&nbsp;", $parsednowiki);
	$parsednowiki = preg_replace("/\n/","<br />\n", $parsednowiki);
	$nowikitext[$nowikicounter] = $parsednowiki;
	$res = "<<ThisIsThePlaceOfTheNoWikiText-$nowikicounter>>";
	$nowikicounter++;
	return $res;
}


function nwiki_parse_header($matches) {
	global $tocheaders, $hindex, $pagename, $content;
	
	$parsed_header = "";
	// the first header will be preceeded by the TOC
	if (!$tocheaders) $parsed_header .= "NWikiTableOfContents\n";
	$parsed_header .= "</p>";
	
    // $matches[0] contains the full expresion
    // $matches[1] contains the expresion without the tags
	$cat = (strlen($matches[0]) - strlen($matches[1])) / 2;
	//the header includes an anchor, to come from the TOC
	$headername = trim($matches[1]);

    // add the header to the TOC
    $headernum  = sizeof($tocheaders) + 1;
	$tocheaders[] = array($cat, $headername, $headernum);

	$elem = ($cat <= 6) ? "h$cat" : "h6"; 
    
	
    // add an edit link in the section header
    $parsed_header .= "<$elem class=\"nwiki\" id=\"$headernum\">"; 
    
    $parsed_header .= $headername."</$elem>".'<p>';
    return $parsed_header;
}

function nwiki_parse_toc($tocheaders) {
	$toc = "<div class=\"toc\">\n" . get_string('toc','wiki');
	$lastlevel = 0;
	$levels = array();
	foreach ($tocheaders as $tocline) {
		while ($tocline[0] < $lastlevel) {
			$lastlevel = array_pop($levels);
			$toc .= "</li></ol>";
		}
		if ($tocline[0] > $lastlevel) {
			array_push($levels, $lastlevel);
			$lastlevel = $tocline[0];
			$toc .= "<ol><li>";
		}
		$toc .= "</li><li><a href=\"#" . $tocline[2] . "\">" . $tocline[1] . "</a>";
	}
	// Remove introduced empty items
	$toc = str_replace("<li></li>", "", $toc);
	$toc = str_replace("</ol><ol>", "", $toc);
	return "</p>" . $toc . str_repeat("</li></ol>", count($levels)) . "</div><p>";
}


function nwiki_parse_internal_link($matches) {
                
    // allow spaces before and after the internal link name
    $matches[1] = trim($matches[1]);
    $matches[1] = wiki_clean_name($matches[1]);

	$parts  = explode('|', $matches[1]);
	$target = $parts[0];
	$label  = $target;
	if (count($parts) > 1) {
		$label = $parts[1];
	}
	
    // internal links to sections 
    $page       = $target;
    $anchor     = '';
    $anchortype = 0;
    $pos        = strpos($target, '#');
    if ($pos > 0)
    {
        $page = substr($target, 0, $pos);
        if (substr($target, $pos + 1, 1) == "#")
        {
            // [[page##section]]: partial view of the section
            $anchortype = 2;
            $anchor = substr($target, $pos + 2, strlen($target) - $pos);
        } else {
            // [[page#section]]: page view plus scroll to section
            $anchortype = 1;
            $anchor = substr($target, $pos + 1, strlen($target) - $pos);
        }
    }

	// we can have more than one section with the same name, so we link
	// to all of them in a list after the link.
    $res      = '';
    $urls     = nwiki_view_page_url($page, $anchor, $anchortype);
    $num_urls = count($urls);
	for ($i = 0; $i < $num_urls; $i++) {
	    if ($i == 0 && $num_urls == 1) { //link to another page
	        $res = "[$urls[$i]]";
	    } elseif ($i == 0) {    // we render the first matched section as a normal link
	    	$res  = '<a href="'.$urls[$i].'">'.$label.'</a>';
	    } elseif ($i == 1) {
	        $res .= ' [<a href="'.$urls[$i].'">'.($i + 1).'</a>';
	    } else {
	        $res .= ', <a href="'.$urls[$i].'">'.($i + 1).'</a>';
	    }
	
	    if (($i == ($num_urls -1)) && ($i > 0)) $res .= ']';
	}
	
    if (!nwiki_page_exists($page)) {
        $res = '<span class="nwikiwanted">'.$res.'</span>';
	} 
    else if ($anchor != '') 
    {
        $res = '<span class="nwikiwanted">'.$res.'</span>';
    }

    return $res;	
}	

/*
 * Parsing anchors 
 */
function nwiki_parse_anchor($matches) {
	
	$parts=explode("|", $matches[1]);
	$target=$parts[0];
	if(count($parts)==2){
		$label=$parts[1];
	}else{
		$label=$target;
	}
	$res="<a href=\"#a". bin2hex($target)."\">".$label."</a>";
	return $res;  
}


/*
 * Parsing external links 
 */
function nwiki_parse_external_link($matches) {
	$url = $matches[2];
	$label = ($matches[4] != '') ? $matches[4] : $url;
	return '<a href="' . $url . '" title="' . $label . '" >' . $label . '</a>';
}

function nwiki_parse_list($matches) {
	$elem_map = array("#" => "ol", "*" => "ul", ":" => "dl");
	$item_map = array("#" => "li", "*" => "li", ":" => "dd");
	
	$html = "";
	$lastlevel = 0;
	$items = array();
	$elems = array();
	
	foreach (explode("\n", $matches[0]) as $item) {
		if (preg_match("/^(\*+|#+|:+)(.*)/", $item, $match)) {
			$elem = $elem_map[substr($match[1], 0, 1)];
			$item = $item_map[substr($match[1], 0, 1)];
			$level = strlen($match[1]);
			
			for (; $level > $lastlevel; $lastlevel++) {
				$html .=  "<$elem><$item>";
				array_push($elems, $elem);
				array_push($items, $item);
			}
			
			for (; $level < $lastlevel; $lastlevel--) {
				$html .=  "</" . array_pop($items) ."></" . array_pop($elems) . ">";
			}
			
			$html .= "</" . array_pop($items) . ">";

			$lastelem = array_pop($elems);
			if ($lastelem != $elem) {
				$html .= "</$lastelem><$elem>";
			}
			array_push($elems, $elem);
			
			$html .= "<$item>" . $match[2];
			array_push($items, $item);
		}
	}
	
	while (count($elems)) {
		$html .=  "</" . array_pop($items) . "></" . array_pop($elems) . ">";
	}
	
	// Remove introduced empty items
	foreach (array_values($item_map) as $item)
		$html = str_replace("<$item></$item>", "", $html);
	
	return "</p>$html<p>";
}

function nwiki_parse_definition_list($matches) {
	$html = '<dl>';
	foreach(explode("\n", $matches[0]) as $line){
		if (preg_match('/^;(.*?):(.*?)$/', $line, $match)) {
			$html .= "<dt>{$match[1]}</dt><dd>{$match[2]}</dd>";
		}
	}
	return "</p>$html</dl><p>";	
}

/* *************************************
 *		REFERENCES & FOOTNOTES
 ************************************* */
function nwiki_parse_references($matches){
	global $references, $nreference;
	$res="";
	$refname=$matches[1];
	if(count($matches)>3){
		$reftext=$matches[3];
	}else{
		$reftext="";
	}

	$nreference++;
	$references[$nreference]= array($refname, $reftext);
	//
	$res="<sup id=\"font$refname\"><a href=\"#target$refname\">$nreference</a></sup>";
		
	return $res;
}

function nwiki_parse_reference_list($matches){
	global $references, $nreference;
	$res="";
	$reflist="<ul>";
	
	$counter=0;
	foreach($references as $ref){
		$refname=$ref[0];
		$reftext=$ref[1];
		$reflist.="<li id=\"target$refname\">$reftext <a href=\"#font$refname\"><sup>$counter</sup></a></li>";
		$counter++;
	}
	$reflist .= "</ul>";
	$res="<div class=\"references\">$reflist</div>";
			
	return "</p>$res<p>";
}

/* *************************************
 *  	FUNCTION TO PARSE TABLES
 ************************************* */
function nwiki_parse_table($matches) {
	$lines = explode("\n", $matches[1]);
	$style = $lines[0];
	
	$elements = array();
	foreach (array_slice($lines, 1) as $line) {
		$line = trim($line);
		$element = Null;
		if (preg_match("/^\|\+(.*)/", $line, $matches)) {
			$element->type = 'caption';
			$element->content = $matches[1];
			array_push($elements, $element); 
		} else if (preg_match("/^\|-(.*)/", $line, $matches)) {
			$element->type = 'row';
			$element->content = "";
			array_push($elements, $element);
		} else if (preg_match("/^\|(.*)/", $line, $matches)) {
			$element->type = 'cells';
			$element->content = $matches[1];
			array_push($elements, $element);
		} else if (preg_match("/^!(.*)/", $line, $matches)) {
			$element->type = 'headings';
			$element->content = $matches[1];
			array_push($elements, $element);
		} else if ($elements) {
			$elements[count($elements)-1]->content .= "\n$line";
		}
	}
	
	$caption = "";
	$rows = array("");
	foreach ($elements as $element) {
		if ($element->type == 'caption') {
			$caption = $element->content;
		} else if ($element->type == 'row') {
			array_push($rows, "");
		} else {
			$sep = ($element->type == 'cells') ? '|' : '!';
			$elt = ($element->type == 'cells') ? 'td' : 'th';
			$cells = explode($sep . $sep, $element->content);
			foreach ($cells as $cell) {
				$cell = strpos($cell, $sep) ? explode($sep, $cell, 2) : array("", $cell);	
				$cell = "<$elt {$cell[0]}>{$cell[1]}</$elt>";
				$rows[count($rows)-1] .= $cell;
			}
		}
	}
	
	$html = "</p>";
	
	// Moodle's format_text remove caption element, so we print it as a p element.
	if ($caption) {
		$html .= "<p>$caption</p>";
	}
	
	$html .= "<table class=\"nwikitable\" $style>";
	
	foreach ($rows as $row) {
		if ($row) {
			$html .= "<tr>$row</tr>";
		}
	}
	$html .= "</table><p>";
	
	return $html;
}

// Table in Creole syntax
function nwiki_parse_creole_table($matches) {
	$res = '</p><table>';
	preg_match_all('/^\|(.*?(\|.*?)*)\|/m', $matches[0], $matches);
	foreach ($matches[1] as $row) {
		$res .= '<tr>';
		foreach (explode('|', $row) as $cell) {
			$res .= ($cell[0] == '=')
				? '<th>' . substr($cell, 1) . '</th>'
				: '<td>' . $cell . '</td>';
		}
		$res .= '</tr>';
	}
	$res .= "</table><p>";
	return $res;
}

/* **************************************************************************

//	A function to parse images properly
//	mediawiki syntax for images:
//	[[Image:{name}|{type}|{location}|{size}|{caption}]]
//	type:		thumb/thumbnail, frame
//	Location:	right, left, center, none
//	Size:		WIDTHpx or WIDTHxHEIGHTpx -> ([0-9]px|[0-9]x[0-9]px)
//	Caption:	any text not identified as one of above.	
//				if the image syntax finish with this: "|]]" caption is not showed
//	Order doesn't matter...

// [[Image:Westminstpalace.jpg|thumb|This text is displayed.|70px|right]]
// <a href="/wiki/Image:Westminstpalace.jpg" title="This text is displayed."><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/39/Westminstpalace.jpg/70px-Westminstpalace.jpg" alt="This text is displayed." width="70" height="53" longdesc="/wiki/Image:Westminstpalace.jpg" /></a>

*/

/*
 *	This function is for the external images.
 */
function nwiki_parse_image($matches) {
	global $CFG, $USER; 
	// the path of the image must be given on the name.
	$alt="";
	$captiontext="";
	$parsedimage="";
	$divclass="";

		// $fields is an array of the fields of the images in mediawiki syntax
		$fields = explode('|', $matches[2]);
		// Let's find which fields have the image	
		$num=count($fields);
		// fields[0] is the full link to the external image
		$imagefullname=$fields[0];
		// let's extract the real name of the image: *.jpg, *.png ...

		$aux=strrchr($imagefullname, "/");
		$imagename=substr($aux, 1, strlen($aux));
		
		$parsedimage="<a href=\"$imagefullname\" title=\"$imagename\" ><img src=\"$imagefullname\" ";		
		foreach ($fields as $field){
			
			if(!strcmp($field,"left")){
				$divclass.=$field;
				$position=$field;
			}
			elseif(!strcmp($field,"right")){
				$divclass.=$field;
				$position=$field;
			}
			elseif(!strcmp($field,"center") or !strcmp($field,"none")){
				$divclass.=$field;
				$position=$field;
			}
			elseif(ereg("(^[0-9]+px)", $field) or ereg("^([0-9]+x[0-9]+px)", $field)){
				//width="XX" height="XX"
				$size=substr($field, 0, strrchr($field, "p"));
				if(strpos($size,"x")){
					$width=substr($size, 0, strrchr($size, "x"));
					$height=substr($size, strrchr($size, "x"), strlen($size));
					$parsedimage.="width=".$width." height=".$height." ";	
				}else{
					$width=$size;
					$parsedimage.=" width=".$width." ";
				}
			}
			elseif(!strcmp($field,"thumb") or !strcmp($field,"thumbnail")){
				$divclass=$field.$divclass;
			}
			elseif(!strcmp($field,"frame")){
				$type=$field;
				$parsedimage.="type=".$type." ";
			}
			elseif(strcmp($field,$imagename) and strcmp($field, $fields[0])){
				//is caption text
				$alt=$field;
			}
		}
		// if the last field is empty "...|]]" caption text is not showed
		if (count($fields) <= 1 || $fields[$num-1]==""){
			//the alt text is the name of the image
			$parsedimage.=" alt=\"".$imagename."\" ";
			$captiontext="";
		}
		else{
			if(strcmp($alt, "")){
				$parsedimage.=" alt=\"".$alt."\" ";
				$captiontext="<div class=\"imgcaption\" > $alt </div>";	
			}
		}
	
	return "</p><div class=\"img$divclass\" >$parsedimage/></a>$captiontext</div><p>";
}

// External images in Creole syntax.
function nwiki_parse_creole_image($matches) {
	$url = $matches[1];
	$alt = isset($matches[4]) ? $matches[4] : '';
	return'<img src="' . $url . '" alt="' . $alt . '" />';
}

function nwiki_parse_attach($matches) {

		$fields = explode('|', $matches[2]);
		// Let's find which fields have the image	
		$attachname = $fields[0];
		
		return "[internal://$attachname]";
}


/**
 * Private function.
 * 
 * This function moves uploaded files to the new path for each wiki
 *  
 * @param integer $wikiid. New wiki id.
 * @param integer $courseid. Course id
 * @param integer $coursemodule Wiki course module
 * @param integer $entryid. Wiki entry id
 * @param string  $pagename. Wiki page name
 * 
 * @return boolean. true in success or false in error
 */
function nwiki_move_uploaded_files($wikiid, $courseid, $coursemodule, $entryid, $pagename){

    global $CFG;
	$result = true;
	
	$from = "$CFG->dataroot/$courseid/moddata/wiki$coursemodule";
	$to = "$CFG->dataroot/$courseid/moddata/wiki/$wikiid/$entryid/$pagename";
	if(check_dir_exists($from)){		
		check_dir_exists($to, true, true);
	    $result = nwiki_move_file($from,$to,$entryid, $pagename);
    }
	
	return $result;
}

/**
 * Private function.
 * 
 * This function moves file or directori $from to $to
 * 
 * @param string $from. File path to be moved
 * @param string $to. Destination path.
 * 
 * @return boolean. true in success or false in error
 */
function nwiki_move_file($from, $to, $entryid, $pagename){
	$result = true;
	
	if (is_dir($from)) {
		$files = list_directories_and_files($from);
		if (!empty ($files)) {
		    foreach ($files as $file){
			    $from_file = $from.'/'.$file;
			    if(is_dir($from_file)){
				    nwiki_move_file($from_file, $to);
				    $to_file = $to;
			    } else{
				    $to_file = $to.'/'.$file;
			    }
			
			    $result = $result && nwiki_move_file($from_file, $to_file, $entryid, $pagename);
		    }
		}
		rmdir($from);
	} else {
		$result = copy($from, $to);
		$result = $result && update_meta_info($to, $entryid, $pagename);
		unlink($from);
	}
	return $result;
}

function update_meta_info($filename, $entryid, $pagename) {
   #-- break on empty files
   if (!filesize($filename)) {
      return(false);
   }

   #-- check for image type and size
   $mime_types = array(
      "application/octet-stream",
      "image/gif",
      "image/jpeg",
      "image/png",
      "application/x-shockwave-flash"
   );
   $ext_types = array(
      "bin", "gif", "jpeg", "png", "swf"
   );
   
   list($width, $height, $mime_i, $uu) = @getimagesize($filename);
   
   (!$mime_i) && ($mime_i=0) || ($mime = $mime_types[$mime_i]);

   ($ext = $ext_types[$mime_i]) or ($ext = $ext_types[0]);

   if (!strlen($mime)) {
      $mime = $mime_types[0];
   }
   
   $add_meta["X-Content-Type"] = $mime;
   if (($s = basename($filename)) && (strlen($s) >= 3)
         || ($s = substr(md5(time()+microtime()),0,8) . ".dat"))
   {
         $add_meta["Content-Location"] = $s;
         ($p = 0) or
         ($p = strrpos($s, "/")) and ($p++) or
         ($p = strrpos($s, '\\')) and ($p++);
         $add_meta["Content-Disposition"] = 'attachment; filename="'.urlencode(substr($s, $p)).'"';
   }
   
   #-- store pagename of binary file
   $add_meta["section"] = $pagename;
   
   #-- store size of binary file
   $add_meta["size"] = filesize($filename);
   
   #-- prepare meta data
   $meta = @array_merge(array(
      "class" => $mime_i ? "image" : "file",
      "Content-Type" => $mime,
      "Pragma" => "cache",
   ), $add_meta);

   if ($mime_i) {
      $meta["width"] = $width;
      $meta["height"] = $height;
   }

   $userid = get_field('wiki_entries', 'userid', 'id', $entryid);
   $user = get_record('user', 'id', $userid);
   
   #-- database entry
   $data = new object();
   $data->pagename = "internal://".basename($filename);
   $data->version = "1";
   $data->flags = 1<<1 | 1<<4; 
   $data->author = "$user->firstname $user->lastname";
   $data->userid = $userid;
   $data->created = time();
   $data->lastmodified = time();
   $data->meta = serialize($meta);
   $data->wiki = $entryid;
   
   $id = insert_record('wiki_pages', $data);
   
   return $id;
}

function nwiki_get_real_pagename ($name, $wikiid, $groupid=null, $ownerid=null) {
	    $select = "syn='" . addslashes($name) . "' AND dfwiki=$wikiid";
        if (isset($groupid)) {
            $select .= " AND groupid=$groupid";
        }
        if (isset($ownerid)) {
            $select .= " AND ownerid=$ownerid";
        }

	    //watch in synonymous
	    if ($synonymous = get_record_select('wiki_synonymous_old', $select)) {
	        //if there's synonymous search for the original
	        return $synonymous->original;
	    }
		//if isn't a synonymous it will be an original or an uncreated page.
	    return $name;
}

function nwiki_view_page_url($pagename, $anchor='', $anchortype=0) {
    global $content, $wikiid, $groupid, $userid;
    
    $module = get_record('modules', 'name', 'wiki');
    $coursemodule = get_record('course_modules', 'instance', $wikiid, 'module', $module->id);
    
    // support page synonyms
    $realpagename = nwiki_get_real_pagename($pagename, $wikiid, $groupid, $userid);
    $urls = array();

	$sectionnums = nwiki_get_section_positions($content, $anchor);

    if ($anchortype > 0 && (count($sectionnums) > 0)) {
        if ($anchortype == 1) {        // [[page#section]]
            foreach ($sectionnums as $sectionnum) {
                $newurl = "view.php?id=$coursemodule->id&amp;page=view/".urlencode($realpagename)."&amp;gid=$groupid&amp;uid=$userid#$sectionnum";
                //$newurl = wiki_format_url($newurl);
                $urls[] = $newurl;
            }
        } else if ($anchortype == 2) { // [[page##section]]
            foreach ($sectionnums as $sectionnum) {
                $newurl = "view.php?id=$coursemodule->id&amp;page=view/".urlencode($realpagename)."&amp;gid=$groupid&amp;uid=$userid&amp;section=".urlencode($anchor)."&amp;sectionnum=$sectionnum";
                //$newurl = wiki_format_url($newurl);
                $urls[] = $newurl;
            }
        }
    } else {// no anchor
    	if ($realpagename != $pagename){
    		$newurl = "$pagename | $realpagename"; //[synonym | pagename]
    	} else {
    		$newurl = $pagename;
    	}
        //$newurl = "view.php?id=$coursemodule->id&amp;page=".urlencode($pagename)."&amp;gid=$gid&amp;uid=$uid";
        $urls[] = $newurl;
    }

    return $urls;
}

/**
 * Returns an array with the positions of a section name in a text,
 * if there is only a section with that name returns only an array 
 * with one position.
 *
 * @param  String $text    Text which may contain sections
 * @param  String $section Name of the section
 * @return Array           Contains the positions of the section
 */
function nwiki_get_section_positions($text, $section)
{
    $positions = array();
    $numsections = 0;
    $lines       = explode("\n", $text);
    foreach ($lines as $current_line) {
        if (wiki_get_section_depth($current_line, '(.*)+') > 0)
            $numsections++;
        if (wiki_get_section_depth($current_line, $section) > 0)
            $positions[] = $numsections;
    }

    return $positions;
}

function nwiki_page_exists($name) {
	global $wikiid, $groupid;
	
	return get_field('wiki_pages_old','pagename','dfwiki',$wikiid,'groupid',$groupid);
}
